package kinon.canteen.network.http;

import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;



import io.reactivex.subscribers.ResourceSubscriber;
import kinon.canteen.application.MyApplication;
import kinon.canteen.util.MyShowDialog;
import retrofit2.adapter.rxjava.HttpException;


/**
 * Created by lhqq on 2017-12-20.
 */

public abstract class CommonSubscriber<T> extends
        ResourceSubscriber<T> {

    private TextView mView;
    private String mErrorMsg;
    private boolean isShowErrorState = true;
    private boolean isCloseDialog = false;
    private boolean isToast = true;

    protected CommonSubscriber(){

    }
    protected CommonSubscriber(boolean isToast){
        this.isToast=isToast;
    }

    protected CommonSubscriber(TextView view){
        this.mView = view;
    }

    protected CommonSubscriber(TextView view, String errorMsg){
        this.mView = view;
        this.mErrorMsg = errorMsg;
    }

    protected CommonSubscriber(TextView view,
                               boolean isShowErrorState){
        this.mView = view;
        this.isShowErrorState = isShowErrorState;
    }

    protected CommonSubscriber(TextView view, String errorMsg,
                               boolean isShowErrorState){
        this.mView = view;
        this.mErrorMsg = errorMsg;
        this.isShowErrorState = isShowErrorState;
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(Throwable t) {
        MyShowDialog.closeLoadingDialog();

        Log.e("http", "onError=="+t.getMessage());
        Log.e("http", "toString=="+t.toString());
        if (mErrorMsg != null && !TextUtils.isEmpty(mErrorMsg)) {
            if(isToast){
                Toast.makeText(MyApplication.getInstance(),
                        mErrorMsg, Toast.LENGTH_SHORT).show();
                onFail(t,1000,mErrorMsg);
            }

        } else if (t instanceof ApiException) {
            if(isToast) {
                Toast.makeText(MyApplication.getInstance(),
                        t.getMessage(), Toast.LENGTH_SHORT).show();
                onFail(t, 1001, t.getMessage());
            }
        } else if (t instanceof HttpException) {
            if(isToast) {
                Toast.makeText(MyApplication.getInstance(),
                        "数据加载失败", Toast.LENGTH_SHORT).show();
                onFail(t, 1002, "数据加载失败");
            }
        } else {
            if(isToast){
//                Toast.makeText(MyApplication.getInstance(),
//                        "未知错误", Toast.LENGTH_SHORT).show();
//
            }
            onFail(t,1003,"未知错误");
        }
    }
     public abstract void onFail(Throwable t, int code, String msg );
}
